package br.com.socket.receiver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;

import br.com.socket.core.Main;
import br.com.socket.functions.ListDirectors;
import br.com.socket.functions.ListProcess;
import br.com.socket.transmiter.Cliente;

public class Servidor extends Thread {

	private static final String caracterDeReconhecimento = "@333 ";
	private static final String separador = System
			.getProperty("line.separator");

	public void run() {

		ServerSocket serv = null;
		Socket s = null;
		BufferedReader entrada = null;

		try {
			serv = new ServerSocket(Main.portServer);
			s = serv.accept();
			String funcao = streamToString(s.getInputStream()); 
			entradaReconhecimento(funcao);

		} catch (IOException e) {

		} finally {
			try {
				s.close();
				serv.close();
			} catch (IOException e) {
				
			} catch (NullPointerException ne){
				System.exit(1);
			}
		}
	}

	private String streamToString(InputStream is) throws IOException {
		Writer writer = new StringWriter();
		char[] buffer = new char[1024];
		try {
			Reader reader = new BufferedReader(new InputStreamReader(is));
			int n;
			while ((n = reader.read(buffer)) != -1) {
				writer.write(buffer, 0, n);
			}
		} finally {
			is.close();
		}
		return writer.toString();
	}

	private void entradaReconhecimento(String entrada) {
		if (entrada.contains(caracterDeReconhecimento)) {
			entrada = entrada.substring(caracterDeReconhecimento.length());
			imprimir(entrada);
		} else {
			executarChamada(entrada);
		}
	}

	private void imprimir(String entrada) {
		for (String e : entrada.split(separador)) {
			System.out.println(e);
		}
	}

	private void executarChamada(String f) {
		switch (f.trim()) {
		case "Listar Processos":
			enviarProcessos();
			break;
		case "Listar Diretorio":
			enviarArquivos();
			break;
		default:
			break;
		}

	}

	private void enviarArquivos() {
		System.out.println("Listando Arquivos:");
		LinkedList<String> l = (LinkedList<String>) ListDirectors.list();
		StringBuilder saida = new StringBuilder();
		for (String s : l) {
			saida.append(s);
			saida.append(separador);
		}
		send(saida.toString());
	}

	private void enviarProcessos() {
		LinkedList<String> l = (LinkedList<String>) ListProcess
				.listarProcessos();
		StringBuilder saida = new StringBuilder();
		for (String s : l) {
			saida.append(s);
			saida.append(System.getProperty("line.separator"));
		}
		send(saida.toString());
	}

	private void send(String s) {
		s = caracterDeReconhecimento + s;
		new Cliente(s, Main.portCliente).start();

	}
}
